import { _decorator, Component, Node,game } from 'cc';
import EventManager from '../../Runtime/EventManger';
import { CONTROLLER_ENUM, EVENT_ENUM, SHAKE_TYPE_ENUM } from '../../Enums';
const { ccclass, property } = _decorator;

@ccclass('ShakeManager')
export class ShakeManager extends Component {
  private isShaking=false
  private type:SHAKE_TYPE_ENUM
  private oldTime:number=0
  private oldPos:{x:number,y:number}={x:0,y:0}

  init(){
    EventManager.Instance.on(EVENT_ENUM.SCREEN_SHAKE,this.onShake,this)
  }

  onDestroy(){
    EventManager.Instance.off(EVENT_ENUM.SCREEN_SHAKE,this.onShake)
  }

  stop(){
    this.isShaking=false
  }
  onShake(type:SHAKE_TYPE_ENUM){
    console.log('触发震动')
    if(this.isShaking){
      return
    }
    this.type=type
    this.oldTime=game.totalTime
    this.isShaking=true
    this.oldPos.x=this.node.position.x
    this.oldPos.y=this.node.position.y
  }

  update(){
    if(this.isShaking){
      const duration=200
      const amount=10
      const frequency=12
      const cursecond=(game.totalTime-this.oldTime)/1000
      const totalSecond=duration/1000
      const offSet=amount*Math.sin(frequency*Math.PI*cursecond)

      if(this.type===SHAKE_TYPE_ENUM.TOP){
        this.node.setPosition(this.oldPos.x,this.oldPos.y-offSet)
      }else if(this.type===SHAKE_TYPE_ENUM.BOTTOM){
        this.node.setPosition(this.oldPos.x,this.oldPos.y+offSet)
      }else if(this.type===SHAKE_TYPE_ENUM.LEFT){
        this.node.setPosition(this.oldPos.x-offSet,this.oldPos.y)
      }else if(this.type===SHAKE_TYPE_ENUM.RIGHT){
        this.node.setPosition(this.oldPos.x+offSet,this.oldPos.y)
      }

      if(cursecond>totalSecond){
        this.isShaking=false
        this.node.setPosition(this.oldPos.x,this.oldPos.y)
      }
    }
  }
}
